//
//  ManagerShareCardController.m
//  QRMaster
//
//  Created by myApple on 15/8/3.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "ManagerShareCardController.h"
#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "CommunityShareCardCell.h"
#import "communityShareCardModel.h"
#import "Reachability.h"
#import "MJRefresh.h"
#import "ManagerShareHistroyController.h"
#import "StartPageController.h"
#import "CommunityListModel.h"
#import "CommunityListInfo.h"

@interface ManagerShareCardController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
    UITableView * shareCardTableView;
    NSMutableArray * shareCardArray;
    UIActivityIndicatorView * _activityIndicator;
    UIImageView * promtBackView;
    UISearchBar * searchBarShare;
    NSInteger pageIndex;
    NSInteger totalPageIndex;
    UISearchDisplayController * shareSearchDisplay;
    NSMutableArray * searchData;
    UIButton * histroyBtn;
    __block NSMutableArray * comListInfoArray;
}

@end

@implementation ManagerShareCardController

- (void)viewDidLoad {
    [super viewDidLoad];
    pageIndex = 1;
    totalPageIndex = 1;
    // Do any additional setup after loading the view.
    self.view.backgroundColor = RGBA(237, 238, 241, 1);
    self.title = NSLocalizedString(@"todayShare", nil);
    shareCardArray = [[NSMutableArray alloc]init];
    searchData = [[NSMutableArray alloc]init];
    comListInfoArray = [[NSMutableArray alloc]init];
    [self getCommunityAreaCode];
    [self prepareTitleView];
    [self prepareTableView];
    [self preparePromtView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    histroyBtn.hidden = NO;
    [self prepareData];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    histroyBtn.hidden = YES;
}

-(void)getCommunityAreaCode
{
    CommunityListInfo * comListInfo = [[CommunityListInfo alloc]init];
    [comListInfo queryAllCommunityInfoBlock:^(NSMutableArray *communityListInfoArray) {
        comListInfoArray = communityListInfoArray;
    }];
}

-(void)prepareTitleView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = ScreenWidth - 80;
    float y = 2;
    float width = 80;
    float height = 40;

    histroyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    histroyBtn.frame = CGRectMake(x, y, width, height);
    [histroyBtn setTitle:NSLocalizedString(@"histroyShare", nil) forState:0];
    [histroyBtn setTitleColor:[UIColor whiteColor] forState:0];
    histroyBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [histroyBtn addTarget:self action:@selector(lookHistroy:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:histroyBtn];
    
    searchBarShare = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
    searchBarShare.delegate = self;
    searchBarShare.placeholder = NSLocalizedString(@"shareSearchContent", nil);
    [self.view addSubview:searchBarShare];
    
    shareSearchDisplay = [[UISearchDisplayController alloc]initWithSearchBar:searchBarShare contentsController:self];
    shareSearchDisplay.searchResultsDataSource = self;
    shareSearchDisplay.searchResultsDelegate = self;
    
}

-(void)lookHistroy:(UIButton *)btn
{
    ManagerShareHistroyController * mscc = [[ManagerShareHistroyController alloc]init];
    mscc.communityId = _communityId;
    mscc.comListArray = comListInfoArray;
    [self.navigationController pushViewController:mscc animated:YES];
}

-(void)preparePromtView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight;
    promtBackView = [[UIImageView alloc]initWithFrame:CGRectMake(x,y, width, height)];
    promtBackView.backgroundColor = RGBA(237, 238, 241, 1);
    promtBackView.userInteractionEnabled = YES;
    promtBackView.hidden = YES;
    [self.view addSubview:promtBackView];
    UITapGestureRecognizer * imgViewTap  = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backViewClick:)];
    [promtBackView addGestureRecognizer:imgViewTap];
    
    x = 0;
    width = ScreenWidth;
    y = ScreenHeight / 2.0 - 10;
    height = 20;
    UILabel * promtLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    promtLabel.text = NSLocalizedString(@"clickRefresh", nil);

    promtLabel.textColor = RGBA(143, 147, 148, 1);
    promtLabel.textAlignment = NSTextAlignmentCenter;
    [promtBackView addSubview:promtLabel];
    
}

-(void)backViewClick:(UITapGestureRecognizer *)tap
{
    promtBackView.hidden = YES;
    [self prepareData];
}

-(void)prepareData
{
    if ([self IsHaveNetwork]) {
        [shareCardTableView.mj_header endRefreshing];
        [shareCardTableView.mj_footer endRefreshing];
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:@"1" forKey:@"today"];
    [postDict setValue:_communityId forKey:@"communityId"];
    [rnk initWithPath:POST(GETCOMMUNITYSHARELIST) params:postDict block:^(id downLoadData, id error) {
        [self stopWaiting];
        NSDictionary * data = [downLoadData objectForKey:@"data"];
        if (data != nil) {
            if (pageIndex == 1) {
                [shareCardArray removeAllObjects];
            }
            NSDictionary * pageDict = [data objectForKey:@"page"];
            totalPageIndex = [[pageDict objectForKey:@"total"] integerValue];
            NSArray * communityInfo = [data objectForKey:@"infos"];
            for (NSDictionary * dict in communityInfo) {
                communityShareCardModel * model = [[communityShareCardModel alloc]init];
                model.shareId = [dict objectForKey:@"id"];
                model.communityId = [dict objectForKey:@"communityId"];
                model.communityName = [dict objectForKey:@"communityName"];
                model.bulidingName = [dict objectForKey:@"buildName"];
                model.floorName = [dict objectForKey:@"floorName"];
                model.roomName = [dict objectForKey:@"roomName"];
                model.beginTime = [dict objectForKey:@"startTime"];
                model.endTime = [dict objectForKey:@"endTime"];
                model.status = [[dict objectForKey:@"status"]intValue];
                model.telePhone = [dict objectForKey:@"mobile"];
                model.shareCardUserName = [dict objectForKey:@"createrName"];
                model.shareCardTime = [dict objectForKey:@"addTime"];
                model.shareAreaCode = [dict objectForKey:@"areaCode"];
                [shareCardArray addObject:model];
            }
            if (shareCardArray.count == 0) {
                promtBackView.hidden = NO;
                [PromptInfoView showMessage:NSLocalizedString(@"noShareList", nil)];
            }
            else
            {
                promtBackView.hidden = YES;
            }
        }
        else if (error != nil) {
            
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
            
        }
        [shareCardTableView.mj_header endRefreshing];
        [shareCardTableView.mj_footer endRefreshing];
        [self stopWaiting];
        [shareCardTableView reloadData];
    }];
    
    
}

-(void)prepareTableView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight;
    
    shareCardTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height -64) style:UITableViewStylePlain];
    shareCardTableView.dataSource = self;
    shareCardTableView.delegate = self;
    shareCardTableView.tableFooterView = [[UIView alloc]init];
    shareCardTableView.tableHeaderView = searchBarShare;
    [self.view addSubview:shareCardTableView];
    __weak ManagerShareCardController * weakSelf = self;
    [shareCardTableView.mj_header beginRefreshing];
    shareCardTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        pageIndex = 1;
        [weakSelf prepareData];
    }];
    [shareCardTableView.mj_footer beginRefreshing];
    shareCardTableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        if (pageIndex >= totalPageIndex) {
            [PromptInfoView showMessage:NSLocalizedString(@"noMoreShareInfo", nil)];
            [shareCardTableView.mj_footer endRefreshing];
        }
        else
        {
            pageIndex ++;
            [self prepareData];
        }
        
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == shareCardTableView) {
        return shareCardArray.count;
    }
    else
        return searchData.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString * cellIdentifier = nil;
    NSMutableArray * tmpArr = [[NSMutableArray alloc]init];
    if (tableView == shareCardTableView) {
        tmpArr = shareCardArray;
        cellIdentifier = @"cell";
    }
    else
    {
        tmpArr = searchData;
        cellIdentifier = @"shareCell";
    }
    CommunityShareCardCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[CommunityShareCardCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    if (tmpArr.count > indexPath.row) {
        communityShareCardModel * model = tmpArr[indexPath.row];
        cell.communityName = model.communityName;
        cell.communityId = model.communityId;
        cell.bulidingName = model.bulidingName;
        cell.floorName = model.floorName;
        cell.roomName = model.roomName;
        cell.beginTime = model.beginTime;
        cell.endTime = model.endTime;
        cell.status = model.status;
        cell.shareCardUserName = model.shareCardUserName;
        for (CommunityListModel * comModel in comListInfoArray) {
            if ([comModel.communityId isEqualToString:model.communityId]) {
                if ([model.shareAreaCode isEqualToString:comModel.areaCodeString]) {
                    cell.telePhone = model.telePhone;
                }
                else
                {
                    cell.telePhone = [NSString stringWithFormat:@"+%@ %@",model.shareAreaCode,model.telePhone];
                }
            }
        }
        
    }
    return cell;
}

#pragma mark -- searchDelegate
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [searchData removeAllObjects];
    for (communityShareCardModel * model in shareCardArray) {
        if (([model.shareCardUserName rangeOfString:searchText].location != NSNotFound)||([model.telePhone rangeOfString:searchText].location != NSNotFound)||([model.shareCardTime rangeOfString:searchText].location != NSNotFound)) {
            [searchData addObject:model];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
